package com.eight.cloud.openapi.util;


import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @ClassName: SignatureUtil
 * @Description: 数据签名工具类
 * @Author: TXC
 * @Date: 2024-10-18 10:48
 **/
public class SignatureUtil {
	/**
	 * 生成签名
	 *
	 * @param secretKey 密钥
	 * @param data 数据
	 * @return java.lang.String
	 * @Author: TXC
	 * @Date: 2024/12/18 10:53
	 */
	public static String generateSignature(String secretKey, String data) {
		try {
			String message = secretKey + data;
			byte[] rawHmac = generateHmac(message, secretKey);
			return bytesToHex(rawHmac);
		} catch (InvalidKeyException | NoSuchAlgorithmException e) {
			throw new RuntimeException("签名算法异常", e);
		}
	}
	/**
	 * @Description: HmacSHA256算法加密
	 *
	 * @param message 需要加密的数据
	 * @param secretKey 密钥
	 * @return java.lang.String
	 * @Author: TXC
	 * @Date: 2024/12/18 10:50
	 */
	private static byte[] generateHmac(String message, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException {
		Mac mac = Mac.getInstance("HmacSHA256");
		SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
		mac.init(secretKeySpec);
		return mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
	}

	/**
	 * 字节数组转16进制字符串
	 * @param bytes 字节数组
	 * @return
	 */
	private static String bytesToHex(byte[] bytes) {
		StringBuilder result = new StringBuilder();
		for (byte b : bytes) {
			result.append(String.format("%02x", b));
		}
		return result.toString();
	}

	/**
	 * 校验签名
	 * @param secretKey 密钥
	 * @param data 数据
	 * @param signature 签名
	 * @return 校验结果
	 */
	public static boolean verifySignature(String secretKey, String data, String signature) {
		return generateSignature(secretKey, data).equals(signature);
	}

}
